import {
  Box,
  Flex,
  Text,
  Radio,
  RadioGroup,
  Button,
  useColorModeValue,
  Tooltip,
  useToast,
  Grid,
  NumberInput,
  NumberInputField,
  NumberInputStepper,
  NumberIncrementStepper,
  NumberDecrementStepper,
} from "@chakra-ui/react";
import { useContext, useState } from "react";
import { MainContext } from "@/src/providers/MainProvider";
import { MacroProfile } from "@/src/types/types";

interface MacroKeySettingProps {
  selectedKeyIndex: number;
  fnLayer: number;
  onSave: (macroIndex: number, macroType: number, loopCount?: number) => void;
}

function MacroKeySetting({ selectedKeyIndex, fnLayer, onSave }: MacroKeySettingProps) {
  const { t, macroProfiles } = useContext(MainContext);
  const [selectedMacro, setSelectedMacro] = useState<number>(-1);
  const [selectedMacroType, setSelectedMacroType] = useState<number>(0);
  const [loopCount, setLoopCount] = useState<number>(1);
  const toast = useToast();
  
  // 计算样式
  const bgColor = useColorModeValue('rgba(255, 255, 255, 0.5)', 'rgba(30, 30, 35, 0.5)');
  const textColor = useColorModeValue('#333', '#E2E8F0');
  const selectedColor = 'rgb(255, 140, 0)';
  const borderColor = useColorModeValue('rgba(255, 165, 0, 0.2)', 'rgba(255, 165, 0, 0.3)');
  const cardBgColor = useColorModeValue('rgba(255, 255, 255, 0.9)', 'rgba(255, 255, 255, 0.1)');

  // 宏类型选项
  const macroTypes = [
    {
      value: 0,
      label: t("518"), // "执行一次"
    },
    {
      value: 2,
      label: t("516"), // "按住重复"
    },
    {
      value: 3,
      label: t("517"), // "任意键停止"
    }
  ];

  // 处理保存
  const handleSave = () => {
    if (selectedMacro === -1) {
      toast({
        title: t("warning"),
        description: t("select_macro_first"),
        status: "warning",
        duration: 2000,
        isClosable: true,
        position: "top",
        variant: "subtle",
        containerStyle: {
          backdropFilter: "blur(10px)",
        },
      });
      return;
    }

    onSave(selectedMacro, selectedMacroType, selectedMacroType === 0 ? loopCount : undefined);
  };

  return (
    <Flex gap={2} h="100%" minH="400px">
      {/* 宏列表 */}
      <Box 
        flex="1"
        p={4}
        borderRadius="12px"
        bg={bgColor}
        border="1px solid"
        borderColor={borderColor}
        backdropFilter="blur(8px)"
        boxShadow="0 2px 8px rgba(0, 0, 0, 0.05)"
        overflowY="auto"
        minH="300px"
        css={{
          '&::-webkit-scrollbar': {
            width: '6px',
          },
          '&::-webkit-scrollbar-track': {
            background: 'rgba(255, 255, 255, 0.1)',
            borderRadius: '8px',
          },
          '&::-webkit-scrollbar-thumb': {
            background: 'rgba(255, 165, 0, 0.3)',
            borderRadius: '8px',
          },
        }}
      >
        <Text
          fontSize="md"
          fontWeight="medium"
          mb={3}
          color={textColor}
        >
          {t("529")} {/* "宏列表" */}
        </Text>
        
        <Grid templateColumns="repeat(auto-fill, minmax(120px, 1fr))" gap={2}>
          {macroProfiles.map((macro, index) => (
            <Box
              key={index}
              p={3}
              borderRadius="8px"
              bg={cardBgColor}
              cursor="pointer"
              border="1px solid"
              borderColor={selectedMacro === index ? selectedColor : "transparent"}
              onClick={() => setSelectedMacro(index)}
              transition="all 0.2s"
              _hover={{
                bg: "rgba(255, 165, 0, 0.1)",
                transform: "translateY(-1px)",
                boxShadow: "0 2px 8px rgba(255, 165, 0, 0.1)"
              }}
            >
              <Text
                color={textColor}
                fontWeight={selectedMacro === index ? "bold" : "normal"}
                fontSize="sm"
                isTruncated
              >
                {macro.name}
              </Text>
              <Text
                fontSize="xs"
                color={textColor}
                mt={1}
              >
                {macro.list.length} {t("actions")}
              </Text>
            </Box>
          ))}
        </Grid>
      </Box>

      {/* 宏类型选择器 */}
      <Box 
        w="400px"
        flexShrink={0} 
        display="flex" 
        flexDirection="column"
        minH="220px"
      >
        <Box
          p={4}
          borderRadius="12px"
          bg={bgColor}
          border="1px solid"
          borderColor={borderColor}
          backdropFilter="blur(8px)"
          boxShadow="0 2px 8px rgba(0, 0, 0, 0.05)"
          display="flex"
          flexDirection="column"
          minH="100%"
        >
          <Text
            fontSize="md"
            fontWeight="medium"
            mb={3}
            color={textColor}
          >
            {t("515")} {/* "宏执行类型" */}
          </Text>
          
          <Box overflowY="auto" mb={3}>
            <RadioGroup
              value={selectedMacroType.toString()}
              onChange={(val) => setSelectedMacroType(parseInt(val))}
              isDisabled={selectedKeyIndex === -1}
            >
              <Flex direction="column" gap={2}>
                {macroTypes.map((type) => (
                  <Box key={type.value}>
                    <Flex align="center" justify="space-between">
                      <Box
                        as="label"
                        cursor={selectedKeyIndex === -1 ? "not-allowed" : "pointer"}
                        opacity={selectedKeyIndex === -1 ? 0.6 : 1}
                        transition="all 0.2s"
                        _hover={selectedKeyIndex !== -1 ? {
                          bg: "rgba(255, 165, 0, 0.1)",
                          transform: "translateX(4px)"
                        } : undefined}
                        p={2}
                        borderRadius="8px"
                        border="1px solid"
                        borderColor={selectedMacroType === type.value ? selectedColor : "transparent"}
                        bg={selectedMacroType === type.value ? "rgba(255, 165, 0, 0.1)" : "transparent"}
                        flex="1"
                      >
                        <Flex align="center" gap={3}>
                          <Radio
                            value={type.value.toString()}
                            colorScheme="orange"
                            isDisabled={selectedKeyIndex === -1}
                            sx={{
                              '.chakra-radio__control': {
                                borderColor: selectedMacroType === type.value ? selectedColor : 'rgba(255, 165, 0, 0.5)',
                                _checked: {
                                  bg: selectedColor,
                                  borderColor: selectedColor
                                }
                              }
                            }}
                          />
                          <Text
                            color={textColor}
                            fontWeight={selectedMacroType === type.value ? "bold" : "normal"}
                          >
                            {type.label}
                          </Text>
                        </Flex>
                      </Box>
                      {/* 循环次数输入框 */}
                      {type.value === 0 && selectedMacroType === 0 && (
                        <Flex align="center" gap={2} ml={4}>
                          <NumberInput
                            value={loopCount}
                            onChange={(_, value) => setLoopCount(value)}
                            min={1}
                            max={255}
                            w="80px"
                            size="sm"
                          >
                            <NumberInputField 
                              bg={cardBgColor}
                              borderColor={borderColor}
                              _hover={{ borderColor: selectedColor }}
                              _focus={{ borderColor: selectedColor, boxShadow: `0 0 0 1px ${selectedColor}` }}
                            />
                            <NumberInputStepper>
                              <NumberIncrementStepper borderColor={borderColor} />
                              <NumberDecrementStepper borderColor={borderColor} />
                            </NumberInputStepper>
                          </NumberInput>
                          <Text fontSize="sm" color={textColor} whiteSpace="nowrap">
                            {t("519")} {/* "循环次数" */}
                          </Text>
                        </Flex>
                      )}
                    </Flex>
                  </Box>
                ))}
              </Flex>
            </RadioGroup>
          </Box>

          <Button
            w="100%"
            colorScheme="orange"
            color="white"
            bg="linear-gradient(135deg, rgb(255, 140, 0) 0%, rgb(255, 165, 0) 100%)"
            _hover={{
              bg: "rgba(255, 165, 0, 0.8)",
              transform: "translateY(-1px)",
              boxShadow: "0 4px 12px rgba(255, 165, 0, 0.2)"
            }}
            _active={{
              bg: "rgba(255, 165, 0, 0.9)",
              transform: "translateY(0)",
              boxShadow: "0 2px 6px rgba(255, 165, 0, 0.2)"
            }}
            isDisabled={selectedKeyIndex === -1 || selectedMacro === -1}
            onClick={handleSave}
            transition="all 0.2s"
            height="40px"
            borderRadius="8px"
            fontWeight="medium"
            fontSize="sm"
            boxShadow="0 2px 8px rgba(255, 165, 0, 0.2)"
            display="flex"
            alignItems="center"
            justifyContent="center"
            opacity={selectedKeyIndex === -1 || selectedMacro === -1 ? 0.6 : 1}
            pointerEvents={selectedKeyIndex === -1 || selectedMacro === -1 ? "none" : "auto"}
          >
            {t("save")}
          </Button>
        </Box>
      </Box>
    </Flex>
  );
}

export default MacroKeySetting; 